package cn.my.framework.config.security;

import cn.my.framework.common.entity.User;
import cn.my.framework.common.service.UserPermService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by zhangl_lc on 2017/7/5.
 */
@Service("myUserDetailService")
public class MyUserDetailsService implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Autowired
    UserPermService permService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("loadUserByUsername >> username = {}",username);
        User user = permService.findUser(username);
        if(user != null){
            Set<GrantedAuthority> authorities = new HashSet<>();
            permService.listRoles(username).forEach(r ->{
                authorities.add(new SimpleGrantedAuthority(r.getCode()));
            });
            return new org.springframework.security.core.userdetails.User(
                    username,user.getPassword(),true,true,true,
                    "1".equals(user.getStatus()),authorities);
        }else{
            throw new UsernameNotFoundException("用户不存在或者密码错误");
        }
    }
}
